import os

from flask import url_for, render_template, request, redirect, flash, make_response, send_file

from cn.wubo.File import File
from cn.wubo.VideoStream import VideoStream
from cn.wubo.util.Util import allowed_file, is_none, get_value


def init_app_route(app):
    from cn.wubo.model import models
    from app import db

    @app.route('/')
    def reindex():
        return redirect(url_for('index'))

    @app.route('/index')
    def index():
        return render_template('index.html', list=models.FileKey.query.all())

    @app.route('/delete/<id>/<ufid>')
    def delete(id, ufid):
        file_key = models.FileKey.query.filter_by(id=id).one_or_none()
        db.session.delete(file_key)
        upload_file = models.UploadFile.query.filter_by(id=ufid).one_or_none()
        if upload_file is not None:
            path = upload_file.filepath
            os.remove(path)
            db.session.delete(upload_file)
            db.session.commit()
        # db.session.delete(upload_file)
        # db.session.commit()
        return render_template('index.html', list=models.FileKey.query.all())

    @app.route('/stream/<key1>/<key2>/<key3>')
    def stream(key1, key2, key3):
        app.logger.info('stream传入参数key1:%s key2:%s key3:%s', key1, key2, key3)
        vs = VideoStream(key1, key2, key3)
        res, mes = vs.check_file(models)
        if not res:
            flash(mes)
            redirect(request.url)
        return render_template('stream.html', url=vs.get_url(mes))

    @app.route("/download/<key1>/<key2>/<key3>", methods=['GET'])
    def download_file(key1, key2, key3):
        app.logger.info('download_file传入参数key1:%s key2:%s key3:%s', key1, key2, key3)
        vs = VideoStream(key1, key2, key3)
        res, mes1, mes2 = vs.check_download_file(models)
        if not res:
            flash(mes1)
            redirect(request.url)
        response = make_response(send_file(mes1, as_attachment=True))
        response.headers["Content-Disposition"] = "attachment; filename={}".format(mes2.encode().decode('latin-1'))
        return response

    @app.route('/upload', methods=['POST', 'GET'])
    def upload():
        if request.method == 'POST':
            if 'file' not in request.files:
                flash('请先选择文件')
                return redirect(request.url)
            file = request.files['file']
            form = request.form
            if is_none('key1', form) and is_none('key2', form) and is_none('key3', form):
                flash('至少输入一项关键字')
                return redirect(request.url)
            if file.filename == '':
                flash('请先选择文件')
                return redirect(request.url)
            if not allowed_file(file.filename):
                flash('不支持的文件类型')
                return redirect(request.url)
            if file and allowed_file(file.filename):
                temp = File(file, get_value('key1', form), get_value('key2', form), get_value('key3', form))
                res, mes = temp.file_check(models)
                if not res:
                    flash(mes)
                    return redirect(request.url)
                res, mes = temp.file_save(models, db)
                flash(mes)
                return redirect(request.url)
        return render_template('upload.html')
